<script setup>
import { ref, reactive, onMounted } from "vue";
import FromCalendar from "./travel/FromCalendar.vue";
import Sumpeople from "./travel/Sumpeople.vue";
import Place from "./travel/Place.vue";
import Name from "./travel/Name.vue";
import Number from "./travel/Number.vue";
import NumberConfirm from "./travel/NumberConfirm.vue";
import { onLoad } from "@dcloudio/uni-app";
const isHide = ref(true);
const baseUrl = "/api";
let id = ref(0);
const navigateToInformation=()=>{

    uni.navigateTo({
        url: '/pages/index'
    });

}

const form = reactive({
  type: 0, // 默认值设为0
  fromDate: "",
  returnDate: "", // 新增返程日期字段
  place: "",
  people: "",
  name: "",
  number: "",
  numberconfirm: "",
});

// 单选框数据
const radiolist1 = reactive([
  {
    name: "去程",
    disabled: false,
  },
  {
    name: "返程",
    disabled: false,
  },
  {
    name: "往返",
    disabled: false,
  },
]);

const radiovalue1 = ref("去程"); // 默认值设为“去程”

const groupChange = (n) => {
  if (n === "去程") {
    form.type = 0;
  } else if (n === "返程") {
    form.type = 1;
  } else {
    form.type = 10;
  }
  console.log(form.type);
};

// 验证验证码是否正确
const Confirm = async () => {
  try {
    let token = uni.getStorageSync("token");
    if (!token) {
      // 验证验证码
      const smsResponse = await uni.request({
        url: baseUrl + "/user/sms/login",
        method: "POST",
        data: {
          phone_number: form.number,
          code: parseInt(form.numberconfirm),
        },
      });

      if (!smsResponse || !smsResponse.data || smsResponse.data.code !== 200) {
        alert("验证码失败");
        console.error(
          "验证码失败:",
          smsResponse && smsResponse.data
            ? smsResponse.data.message || smsResponse.data.error
            : "未知错误"
        );
        return;
      }
      alert("验证码成功");
      token = smsResponse.data.data.access_token;
      uni.setStorageSync("token", token);
    }

    // 获取用户ID
    const userResponse = await uni.request({
      url: baseUrl + "/user/get/user",
      method: "GET",
      header: {
        Authorization: `Bearer ${token}`,
      },
    });

    if (!userResponse || !userResponse.data || userResponse.data.code !== 200) {
      alert("获取用户信息失败");
      console.error(
        "获取用户信息失败:",
        userResponse && userResponse.data
          ? userResponse.data.message || userResponse.data.error
          : "未知错误"
      );
      return;
    }

    const userId = userResponse.data.data.id;

    // 创建订单
    let reservationDate = "";
    if (form.type === 0) {
      form.fromDate = form.fromDate;
    } else if (form.type === 1) {
      form.returnDate = form.returnDate;
    } else if (form.type === 10) {
      form.fromDate = form.fromDate;
      form.returnDate = form.returnDate;
    } else {
      alert("请选择正确的预约类型");
      return;
    }

    console.log("Reservation Date:", reservationDate);
    if (id > 0) {
      const orderResponse = await uni.request({
        url: baseUrl + "/order/update",
        method: "POST",
        header: {
          Authorization: `Bearer ${token}`,
        },
        data: {
          id: id,
          user_id: userId,
          reservation_type: form.type,
          go_date: form.fromDate,
          return_date: form.returnDate,
          passenger_count: form.people,
          pickup_location_id: form.place,
          passenger_name: form.name,
          entry_source: "1234",
          phone_number: form.number,
        },
      });
      if (
        !orderResponse ||
        !orderResponse.data ||
        orderResponse.data.code !== 200
      ) {
        alert(orderResponse.data.message);
        console.error(
          "订单创建失败:",
          orderResponse && orderResponse.data
            ? orderResponse.data.message || orderResponse.data.error
            : "未知错误"
        );
        return;
      }
    } else {
      const orderResponse = await uni.request({
        url: baseUrl + "/order/create",
        method: "POST",
        header: {
          Authorization: `Bearer ${token}`,
        },
        data: {
          go_date: form.fromDate,
          return_date: form.returnDate,
          user_id: userId,
          reservation_type: form.type,
          reservation_date: reservationDate,
          passenger_count: form.people,
          pickup_location_id: form.place,
          passenger_name: form.name,
          phone_number: form.number,
          entry_source: "1234",
        },
      });
      if (
        !orderResponse ||
        !orderResponse.data ||
        orderResponse.data.code !== 200
      ) {
        alert(orderResponse.data.message);
        console.error(
          "订单创建失败:",
          orderResponse && orderResponse.data
            ? orderResponse.data.message || orderResponse.data.error
            : "未知错误"
        );
        return;
      }

      alert("订单创建成功");
      console.log("订单创建成功:", orderResponse.data);
    }

    // 导航到 Content 页面
    uni.navigateTo({
      url: "/pages/Content",
    });
  } catch (error) {
    alert("请求失败");
    console.error("请求失败:", error);
  }
};
onLoad((option) => {
  let token = uni.getStorageSync("token");
  if (token) {
    isHide.value = false;
  }
  if (uni.getStorageSync("order_info")) {
    let order = JSON.parse(uni.getStorageSync("order_info"));
    console.log(order);
    form.people = order.passenger_count;
    isHide.value = false;
    if (order.reservation_type == 0) {
      form.fromDate = order.fromDate.split("T")[0];
      radiovalue1.value = "去程";
    }
    if (order.reservation_type == 1) {
      form.returnDate = order.returnDate.split("T")[0];
      radiovalue1.value = "返程";
    }
    if (order.reservation_type == 10) {
      form.fromDate = order.fromDate.split("T")[0];
      form.returnDate = order.returnDate.split("T")[0];
      radiovalue1.value = "往返";
    }
    form.type = order.reservation_type;
    form.place = order.pickup_location_id;
    form.name = order.passenger_name;
    uni.removeStorageSync("order_info");
    id = order.id;
  }
});
// 页面加载时初始化默认值
onMounted(() => {
  groupChange(radiovalue1.value); // 初始化默认值
});
</script>

<template>
  <div>
    <!-- {{ form }} -->
    <!-- 上传图片 -->
    <div class="header">
      <a
        href="https://1636401myiniulvyou.sjdzp.cn/Miniwx/Index/buy.html?goods_id=12083959"
        target="_blank"
      >
        <img
          src="../static/3445ac5d7bb801146f2cf2ad424c58d.png"
          alt="示例图片"
        />
      </a>
    </div>
    <!-- <div class="img">
      <img src="" alt="" />
    </div> -->

    <!-- 单选框 -->
    <div class="select">
      <div class="Reverse_Type">预约类型:</div>
      <up-radio-group
        v-model="radiovalue1"
        placement="row"
        @change="groupChange(radiovalue1)"
      >
        <up-radio
          :customStyle="{ marginBottom: '8px' }"
          v-for="(item, index) in radiolist1"
          :key="index"
          :label="item.name"
          :name="item.name"
          style="margin-right: 1.3rem; margin-left: 0.3rem"
        >
        </up-radio>
      </up-radio-group>
    </div>
    <!-- 去程日期 -->
    <div class="date" v-if="form.type === 0 || form.type === 10">
      <div class="godate">去程日期:</div>
      <!-- 合并后的表单元素，点击时显示日期选择器 -->
      <div class="date-form">
        <FromCalendar v-model="form.fromDate" />
      </div>
    </div>
    <!-- 返程日期 -->
    <div class="date" v-if="form.type === 1 || form.type === 10">
      <div class="godate">返程日期:</div>
      <!-- 合并后的表单元素，点击时显示日期选择器 -->
      <div class="date-form">
        <FromCalendar v-model="form.returnDate" />
      </div>
    </div>
    <!-- 乘车人数 -->
    <Sumpeople v-model="form.people" />
    <!-- 上车地点 -->
    <Place v-model="form.place" />
    <!-- 联系姓名 -->
    <Name v-model="form.name" />
    <!-- 联系手机号 -->
    <Number v-model="form.number" />
    <!-- 手机验证码 -->
    <NumberConfirm v-if="isHide" v-model="form.numberconfirm" :hide="isHide" />

    <!-- 确定预约按钮 -->
    <div class="flex">
      <up-button
        text="确认预约"
        class="button"
        type="primary"
        size="normal"
        @click="Confirm"
      ></up-button>
    </div>

    <!-- 乘车说明 -->
    <div class="illustrate">
      <div class="illustrate-left"></div>
      <div class="illustrate-body">乘车预约说明</div>
      <div class="illustrate-right"></div>
    </div>
<<<<<<< HEAD
=======
    <p>乘车预约说明内容</p>
      <view>
          <button @click="navigateToInformation">跳转到信息页面</button>
      </view>
>>>>>>> 48d01d0 (first commit)
  </div>
</template>

<style lang="scss" scoped>
.img {
  width: 100%;
  height: 8rem;
  background-color: pink;
}

.select {
  display: flex;
  align-items: center;
  margin-top: 1rem;
}

.Reverse_Type {
  margin-left: 1rem;
  margin-right: 0.6rem;
}

.date {
  display: flex;
  align-items: center;
  margin-top: 1rem;
}

.godate {
  margin-left: 0.4rem;
  padding-left: 0.5rem;
}

.date-form {
  display: flex;
  align-items: center;
  border: 1px solid #ccc;
  padding: 5px;
  margin-left: 1rem;
  cursor: pointer;
  width: 50%;
  /* 调整宽度以适应不同布局 */
}

.date-form .date-input {
  flex: 1;
  border: none;
  outline: none;
  width: 100%;
  /* 输入框占满整个表单 */
  box-sizing: border-box;
  /* 确保内边距不会影响宽度 */
}

.close-button {
  background: none;
  border: none;
  font-size: 16px;
  cursor: pointer;
  color: #999;
  position: absolute;
  top: 0;
  right: 10px;
  z-index: 1;
  /* 确保关闭按钮在日期选择器上方 */
}

.flex {
  margin-top: 1rem;
  display: flex;
  justify-content: center;
}

.button {
  width: 25%;
}

.illustrate {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 1rem;
}

.illustrate-left {
  width: 5rem;
  height: 0.1rem;
  background-color: gainsboro;
}

.illustrate-right {
  width: 5rem;
  height: 0.1rem;
  background-color: gainsboro;
}

p {
  margin-left: 1rem;
  font-size: 0.9rem;
}
.header {
  width: 100%;
  height: 8rem;
  background-color: pink;
  overflow: hidden; // 防止图片超出容器边界
  display: flex;
  justify-content: center;
  align-items: center;
}

.header a {
  display: block;
  width: 100%;
  height: 100%;
}

.header img {
  width: 100%;
  height: 100%;
  object-fit: cover; // 或者使用 contain
}
</style>
